<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>使用立即执行(iife)函数提升性能</title>
  <!-- 整个应用中，只需做一次判断，无需做大量的重复工作的了 -->
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
    }
  </style>
</head>

<body>
  <div></div>
</body>
<script>
  "use strict"; {
    // 判断浏览器支持的事件添加方法，
    function addEvent0(e, eventName, handler) {
      if (e.addEventListener) {
        e.addEventListener(eventName, handler);
      } else if (e.attachEvent) {
        e.attachEvent("on" + eventName, handler)
      } else {
        e["on" + eventName] = handler;
      };
    };

    // 修改以上代码，用户只需做一次判断即可
    let addEvent = (() => {
      // debugger;
      if (window.addEventListener) {
        return function (e, eventName, handler) {
          e.addEventListener(eventName, handler);
        };
      } else if (window.attachEvent) {
        return function (e, eventName, handler) {
          e.attachEvent("on" + eventName, handler);
        };
      } else {
        return function (e, eventName, handler) {
          e["on" + eventName] = handler;
        };
      };
    })();

    // 注册事件了吧
    addEvent(window, "load", () => {
      console.log(`进入了吧`);
    });
  }; {
    /** 发出 http 请求，适配于浏览器和node环境 */
    function request1(options) {
      if (typeof window !== "undefined") {
        // 浏览器端的 ajax

      } else {
        // node的 http
      };
    };

    // 没必要每次都要判断，只需判断一次即可
    let request = (() => {
      if (typeof window !== "undefined") {
        // 浏览器端的 ajax
        return function (options) {

        };
      } else {
        // node的 http
        return function (options) {

        };
      };
    })();
  }; {
    // 移除空格的函数
    function removeSpace1(str) {
      return str.replace(/\s/g, "");
    };

    // 移除所空格，不需每次都创建一次正则表达了
    let removeSpace = (() => {
      let reg = /\s/g;
      return str => {
        return str.replace(reg, "");
      };
    })();

    let res = removeSpace("ndao ndan ");
    console.log(res);
  };
</script>

</html>